import java.io.*;

public class BitOutputStream implements AutoCloseable {
    private FileOutputStream out;
    private byte b = 0;
    private int bitCount = 0;

    public BitOutputStream(File file) throws IOException {
        if (file.exists()) throw new IOException();
        out = new FileOutputStream(file);
    }

    public void close() throws IOException {
        if (bitCount > 0) {
            int repeat = 8 - bitCount;
            for (int i = 1; i <= repeat; i++) writeBit('0');
        }
        out.close();
    }

    public void writeBit(char ch) throws IOException {
        b = (byte) (b << 1);
        bitCount++;
        switch (ch) {
            case '0':
                b += (byte) 0;
                break;
            case '1':
                b += (byte) 1;
                break;
        }
        if (bitCount == 8) {
            out.write(b);
            b = (byte) 0;
            bitCount = 0;
        }
    }

    public void writeBits(String bits) throws IOException {
        for (int i = 0; i <= bits.length() - 1; i++) {
            writeBit(bits.charAt(i));
        }
    }
}
